package cn.jjzd.info.controller;

import cn.jjzd.info.pojo.Category;
import cn.jjzd.info.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService sysCategoryService;

    /**
     * 根据Pid获取分类列表数据
     * @param pid
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<Category>> queryCategoriesByPid(@RequestParam(value = "pid",defaultValue = "0")Long pid){
        if(pid == null || pid < 0){
            //return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            return ResponseEntity.badRequest().build();
        }
        List<Category> categories = this.sysCategoryService.queryCategoriesByPid(pid);
        if(CollectionUtils.isEmpty(categories)){
            //return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(categories);
    }

    @GetMapping("{cid}")
    public ResponseEntity<List<Category>> queryByCid(@PathVariable("cid")Long cid){
        List<Category> categories = this.sysCategoryService.queryNamesByCid(cid);
        if(categories == null && CollectionUtils.isEmpty(categories)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(categories);
    }

    @GetMapping("categoryList")
    public ResponseEntity<List<Category>> queryLastList(@RequestParam("cid")Long cid){
        List<Category> categories = this.sysCategoryService.queryCategoryList(cid);
        if(categories == null && CollectionUtils.isEmpty(categories)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(categories);
    }

    @GetMapping("categoryParentList")
    public ResponseEntity<List<Category>> queryByParentId(@RequestParam("parentId")Long parentId){
        List<Category> categories = this.sysCategoryService.queryCategoriesByPid(parentId);//this.sysCategoryService.queryByParentId(parentId);
        if(categories == null && CollectionUtils.isEmpty(categories)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(categories);
    }

    @PostMapping
    public ResponseEntity<Void> saveInfo(@RequestBody Category category){
        sysCategoryService.saveCategory(category);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @DeleteMapping("delete")
    public ResponseEntity<Void> deleteById(@RequestParam("id")Long id){
        sysCategoryService.deleteById(id);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
}

